import AxiosService from '@/service/axios'
import { EventBus } from '@/utils/'
import 'element-plus/es/components/message/style/css'
import { ElMessage, ElLoading } from 'element-plus'

const API_MAP = {
  sms: '/sms',
  login: '/login',
  logout: '/login/out?target=',
  userInfo: '/user/info',
  regist: '/user/reg',
  reset: '/login/reset'
}
// is mock ?
const isMock = false//process.env.VUE_APP_MOCK == 'true';
const notNeedLoginUrls = ['/file/save'];

// 是否请求结束，防止二次请求；当同一条请求再次过来的时候，会进行判断（false：则执行；true：则阻截；）
const isApiSended = {}
// 请求时 Loading
const options = { 
  fullscreen: true,
  lock: true,
  text: 'Loading',
  background: 'rgba(0, 0, 0, 0.7)', 
}
// 请求地址前缀：域名+头
// export const serverUrl = "https://apib.hd.xxx.com/v1";
const env_ = import.meta.env
const env = {
  webUrl: env_.VITE_APP_WEB_URL,
  apiUrl: env_.VITE_APP_API_URL,
}
export const serverUrl = env.apiUrl
export const localUrl = "/"
export const fileUploadUrl = 'https://sinastorage.com/file.hd.xxx.com/'
export const fileUploadS3Url = serverUrl + '/weibo/picid/'

let loadingInstance: any
/** API
 * [API get/get4Data/post/post4Data]
 */
const arrMockAPI = [  // 暂存 mock api
  '/stat/promt_list',
  '/stat/promt_add',
  '/site/add',
  '/site/save',
  '/site/get',
]

async function get(url: string, params: any, cb: Function) {
  AxiosService.request({
    url: url,
    method: 'get', // 默认是 get
    params: params,
    baseURL: isMock && arrMockAPI.indexOf(url) > -1 ? localUrl : serverUrl,
  }).then(function(response: any) {
    cb(response.data.data)
  }).catch(function(response: any) {
    ElMessage(url + response.data.msg)
  })
}

async function get4Data(url: string, params: any, cb: Function) {
  AxiosService.request({
    url: url,
    method: 'get', // 默认是 get
    params: params,
    baseURL: isMock && arrMockAPI.indexOf(url) > -1 ? localUrl : serverUrl,
  }).then(function(response: any) {
    cb(response.data)
  }).catch(function(response: any) { 
    ElMessage(url + response.data.msg)
  })
}

async function post(url: string, params: any, cb: Function) {
  // isApiSended
  // eslint-disable-next-line no-prototype-builtins
  if(Object.prototype.hasOwnProperty.call(isApiSended, url) && notNeedLoginUrls.indexOf(url) == -1) {
    if(!isApiSended[url]){
      return
    }
  } else {
    isApiSended[url] = false
  }
  // loading
  loadingInstance = ElLoading.service(options)

  return await AxiosService.post(url, params)
    .then(function (response: any) {
      nextTick(() => {
        loadingInstance.close()
      });
      // isApiSended true
      isApiSended[url] = true
      // code
      if(response.data.code == "900001") {
        EventBus.$emit("login")
      }
      if(response.data.code == 0) {
        cb(response.data.data)
      } else {
        if(response.data && response.data.msg) {
          ElMessage(url + response.data.msg)
        }
      }
    })
    .catch(function (response: any) {
      loadingInstance.close()
      nextTick(() => {
        if(response.data && response.data.msg) {
          ElMessage(url + response.data.msg)
        } else {
          ElMessage(response.message)
        }
      })
      isApiSended[url] = true
    })
}

async function post4Data(url: string, params: any, cb: Function) {
  if(Object.prototype.hasOwnProperty.call(isApiSended, url)) {
    if(!isApiSended[url]) {
      return
    }
  } else {
    isApiSended[url] = false
  }
  // loading
  loadingInstance = ElLoading.service(options)
  // post
  return await AxiosService.post(
    url,
    params)
    .then(function (response: any) {
      // loading close
      nextTick(() => {
        loadingInstance.close()
      });
      // isApiSended true
      isApiSended[url] = true
      // code
      if(response.data.code == "900001") {
        EventBus.$emit("login")
      }
      // callback
      cb(response.data)
    })
    .catch(function (response: any) {
      nextTick(() => {
        loadingInstance.close()
        if(response.data && response.data.msg) {
          ElMessage(url + response.data.msg)
        } else {
          ElMessage(response.message)
        }
      })
      cb(response.data)
      isApiSended[url] = true
    })
}

export {
  get,
  get4Data,
  post,
  post4Data,
  API_MAP,
}

